﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace MvcDemo.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        private string _uName = "Demo";

        public ActionResult Index()
        {
    
            return View();
        }
        [HttpPost]
        public void UpLoadPhoto(HttpPostedFileBase file)
        {
            var res = CheckImg(file);
            if (res == "ok")
            {
                var fileName = file.FileName;//Path.GetExtension() 也许可以解决这个问题，先不管了。
                var pathtemp = Path.Combine(Server.MapPath("../Content/TempFile/"), fileName);//先存入临时文件夹
                var scrtemp = Path.Combine("../../Content/TempFile/", fileName);//图片展示的地址

                var list = Session["Imgscr"] as List<string>;
                var slist = Session["ImgServerscr"] as List<string>;
                if (list != null)
                {
                    list.Add(scrtemp);
                }
                else
                {
                    list = new List<string> { scrtemp };
                    Session["Imgscr"] = list;
                }
                if (slist != null)
                {
                    slist.Add(pathtemp);
                }
                else
                {
                    slist = new List<string> { pathtemp };
                    Session["ImgServerscr"] = slist;
                }

                file.SaveAs(pathtemp);
                Response.Write("<img src='../../Content/TempFile/" + fileName + "' /> ");
            }
            else
            {
                Response.Write(res);
            }
        }

        /// <summary>
        /// 删除预览中的照片
        /// </summary>
        /// <param name="str">这个str 已经是处理过的，不是之前上传的图片名称</param>
        public void DeleteImg(string str)
        {
            //删除地址 删除文件
            var list = Session["Imgscr"] as List<string>;
            if (list == null) return;
            var index = list.IndexOf(str);
            var slist = Session["ImgServerscr"] as List<string>;
            if (slist != null && index != -1)
            {
                var imgone = slist[index];
                if (imgone != null)
                {
                    var img = new FileInfo(imgone);
                    if (img.Exists) img.Delete();
                }
            }
            list.Remove(str);
        }

        private string CheckImg(HttpPostedFileBase file)
        {
            if (file == null) return "图片不能空！";
            if (file.ContentLength / 1024 > 8000)
            {
                return "图片太大";
            }
            if (file.ContentLength / 1024 < 10)
            {
                return "图片太小！";
            }
            var image = GetExtensionName(file.FileName).ToLower();
            if (image != ".bmp" && image != ".png" && image != ".gif" && image != ".jpg" && image != ".jpeg")// 这里你自己加入其他图片格式，最好全部转化为大写再判断，我就偷懒了
            {
                return "格式不对";
            }

            var scrtemp = Path.Combine("../../Content/TempFile/", file.FileName);//图片展示的地址
            var list = Session["Imgscr"] as List<string>;
            if (list != null && list.Find(n => n == scrtemp) != null)
            {
                return "同样的照片已经存在！";
            }

            return "ok";
        }

        public JsonResult SaveImgs(string content)
        {
            var uid = CheckValid();
            if (_uName == null) _uName = GetUserNameById(uid);

            string path = Path.Combine(HttpContext.Server.MapPath("../Content/UploadFiles/"), _uName, "Photos", "ImgBox");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var list = Session["Imgscr"] as List<string>;
            var finallist = new List<string>();
            if (list == null) return Json(0);
            foreach (var str in list)
            {
                var scrtemp1 = Server.MapPath(str.Substring(3, str.Length - 3));//去掉第一个../
                var img = new FileInfo(scrtemp1);
                if (img.Exists)
                {
                    var image = GetExtensionName(img.Name);
                    //处理照片名称
                    var imgname = string.Format("{0:yyyMMdd}", DateTime.Now).Replace("/", "") + DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture).Substring(7, 11) + image;
                    var scrdestination = Path.Combine(HttpContext.Server.MapPath("../Content/UploadFiles/"), _uName, "Photos", "ImgBox", imgname);

                    var scrshow = Path.Combine(("../../Content/UploadFiles/"), _uName, "Photos", "ImgBox", imgname);
                    finallist.Add(scrshow);
                    //移动照片
                    img.MoveTo(scrdestination);
                    //存入imgbox
                   // 存入数据库 
                };
            }
            if (finallist.Count() != 0)
            {
                Session.Remove("Imgscr");
                Session.Remove("ImgServerscr");
            }


            return Json(1);
        }
        public string GetExtensionName(string fileName)
        {
            if (fileName.LastIndexOf("\\", StringComparison.Ordinal) > -1)//在不同浏览器下，filename有时候指的是文件名，有时候指的是全路径，所有这里要要统一。
            {
                fileName = fileName.Substring(fileName.LastIndexOf("\\", StringComparison.Ordinal) + 1);//IndexOf 有时候会受到特殊字符的影响而判断错误。加上这个就纠正了。
            }
            return Path.GetExtension(fileName.ToLower());
        }
        private int CheckValid()
        {
            return 1;//返回id 
        }

        private string GetUserNameById(int id)
        {
            return "Demo";
        }
    }
}
